#pragma once

#include <iostream>

#include <sys/time.h>
#include <sys/types.h>
#include <sys/select.h>
#include <unistd.h>
// #include "Log.hpp"
#include "Socket.hpp"

using namespace std;

// Log lg;

static const uint16_t defaultport = 8080;
static const int fd_num_max = (sizeof(fd_set) * 8);
int defaultfd = -1;

class SelectServer
{
public:
    SelectServer(uint16_t port = defaultport)
        : port_(port)
    {
    }
    ~SelectServer()
    {
    }

public:
    bool Init()
    {
        listensock_.Socket();
        listensock_.Bind(port_);
        listensock_.Listen();

        return true;
    }

    void Start()
    {
        int listensock = listensock_.Fd();
        fd_array[0] = listensock;

        while (true)
        {
            fd_set rfds;
            FD_ZERO(&rfds);

            // 多个文件描述符中，获取最大文件描述符，并将这些文件描述符它们设置进 rfds
            int maxfd = fd_array[0];
            for (int i = 0; i < fd_num_max; i++)
            {
                if (fd_array[i] == defaultfd)
                    continue;
                // 有了文件描述符了
                FD_SET(fd_array[i], &rfds);
                if (maxfd < fd_array[i])
                {
                    maxfd = fd_array[i];
                    lg(Info, "max fd updata, max fd is: %d", maxfd);
                }
            }

            // 预备工作——struct timeval
            struct timeval timeout = {1, 0}; // 表示剩下的时间，每隔n秒，检测一次

            // 开始 select
            int n = select(maxfd + 1, &rfds, nullptr, nullptr, &timeout);
            switch (n)
            {
            case 0:
                cout << "time out, timeout: " << timeout.tv_sec << ":" << timeout.tv_usec << endl;
                break;
            case -1:
                cout << "select error" << endl; 
                break;
            default:
                // 有事件就绪了，获取了连接
                cout << "get a new link.." << endl;
                Dispatcher(rfds);   // 就绪后的工作
                break;
            }
        }
    }
private:
    void Printfd()
    {
        cout << "online fd list: ";
        for(int i = 0; i < fd_num_max; i++)
        {
            if(fd_array[i] == defaultfd) continue;
            cout << fd_array[i] << " ";
        }
        cout << endl;
    }

    // 连接管理器
    void Accepter()
    {
        // 连接事件就绪了
        std::string clientip;
        uint16_t clientport;
        int sock = listensock_.Accept(&clientip, &clientport);
        if(sock < 0) return;
        lg(Info, "accept success, %s:%d, sock fd: %d", clientip.c_str(), clientport, sock);

        // accept 成功
        int pos = 1;
        for(; pos < fd_num_max; pos++)
        {
            if(fd_array[pos] != defaultfd)
                continue;
            else
                break;
        }

        if(pos == fd_num_max)
        {
            lg(Warning, "server is full, close %d now", sock);
            close(sock);
        }
        else    // 遇到了 fd_array[pos] == fefault
        {
            fd_array[pos] = sock;
            Printfd();
        }
    }

    // 没有连接
    void Recver(int fd, int pos)
    {
        char buffer[1024];
        ssize_t n = read(fd, buffer, sizeof(buffer));
        if(n > 0)
        {
            buffer[n] = 0;
            cout << "get a message: " << buffer << endl;
        }
        else if(n == 0)
        {
            lg(Info, "client quit, me too, close fd is: %d", fd);
            close(fd);
            fd_array[pos] = defaultfd;
        }
        else
        {
            lg(Warning, "recv error, fd is %d", fd);
            close(fd);
            fd_array[pos] = defaultfd;
        }
    }

    void Dispatcher(fd_set &rfds)
    {
        for(int i = 0; i < fd_num_max; i++)
        {
            int fd = fd_array[i];
            if(fd == defaultfd) continue;

            // 开始执行就绪之后的工作了
            if(FD_ISSET(fd, &rfds)) //判断set集中fd的位是否为真
            {
                if(fd == listensock_.Fd())
                {
                    // 连接管理器
                    Accepter();
                }
                else    // 没有连接
                {   
                    Recver(fd, i);
                }
            }
        }
    }

private:
    Sock listensock_;
    uint16_t port_;
    int fd_array[fd_num_max]; // 多个文件描述符，数组（用户自己维护的）
};
